package com.hefei.blog.base.utils.html;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.nio.charset.Charset;

import org.apache.commons.io.IOUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;

import com.hefei.blog.base.lang.Consts;
import com.hefei.blog.base.upload.consts.FileConsts;
import com.hefei.blog.base.utils.FileNameUtils;
import com.hefei.blog.base.utils.FilePathUtils;

public class FileHtmlUtils {

	private static Logger log = Logger.getLogger(FileHtmlUtils.class);
	
	/**
	 * @param html
	 * @return 存储文件的相对路径
	 */
	public static void write(String html, String relativePathAndName) {
		File file = new File(FileConsts.ROOT_HTML + relativePathAndName);
		FilePathUtils.checkDirAndCreate(file);
		
		try (FileOutputStream fop = new FileOutputStream(file)) {
			// if file doesn't exists, then create it
			if (!file.exists()) {
				file.createNewFile();
			}

			// get the content in bytes
			byte[] contentInBytes = html.getBytes(Charset.forName(Consts.CHARSET));

			fop.write(contentInBytes);
			fop.flush();
			fop.close();
		} catch (Exception e) {
			log.error("ERROR", e);
		}
	}
	
	public static String read(String relativePathAndName){
        try {
        	if(StringUtils.isBlank(relativePathAndName))
        		return null;
        	File file = new File(FileConsts.ROOT_HTML + relativePathAndName);
        	if(file.exists())
        		return IOUtils.toString(new FileInputStream(file), Charset.forName(Consts.CHARSET));
        	return null;
		} catch (Exception e) {
			log.error("ERROR", e);
			return null;
		} 
	}

	public static String getRelativePathAndName() {
		return FilePathUtils.getHtmlPath() + FileNameUtils.randomFileName("html");
	}
}
